package org.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collection;

import com.briup.smart.env.entity.Environment;
import com.briup.smart.env.server.Server;

public class ServerImpl implements Server {
    // 接收客户端数据的方法
    @Override
    public void receive() {
        // 搭建Tcp服务器
        Socket socket = null;
        ServerSocket serverSocket = null;
        int port = 8899;
        ObjectInputStream ois = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("服务端：网络模块成功启动，端口" + port);
            socket = serverSocket.accept();
            System.out.println("服务端：客户端已成功连接" + socket);
            ois = new ObjectInputStream(socket.getInputStream());
            // 读取集合对象
            @SuppressWarnings("unchecked")
            Collection<Environment> coll = (Collection<Environment>) ois.readObject();
            System.out.println("服务端：网络模块，成功接收" + coll.size() + "条数据");

            // 网络模块中接收到数据 直接进行入库
            // 实例化 DBStoreImpl 对象
            DBStoreImpl dbStore = new DBStoreImpl();
            System.out.println("服务端：网络模块，调用数据入库模块");
            // 调用 saveDB 方法 实现接收功能
            dbStore.saveDB(coll);

        } catch (Exception e) {
            // 正确处理异常
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("服务端：网络模块，成功关闭");
        }
    }

    // 关闭服务器的方法
    @Override
    public void shutdown() throws Exception {

    }

}